import speech_recognition as sr
from flask import jsonify

def speech_to_text():
    recognizer = sr.Recognizer()

    with sr.Microphone() as source:
        print("请说话...")
        audio = recognizer.listen(source)

    try:
        print("正在识别...")
        text = recognizer.recognize_google(audio, language='zh-CN')
        print("识别结果:", text)
        return text  # 返回识别的文本
    except sr.UnknownValueError:
        print("抱歉，无法识别音频")
        return None
    except sr.RequestError as e:
        print("请求错误: ", e)
        return None

def speech_to_text_api():
    try:
        text = speech_to_text()
        if text:
            return jsonify({'result': '成功识别语音', 'text': text})
        else:
            return jsonify({'result': '无法识别语音'})
    except Exception as e:
        return jsonify({'result': f"发生错误: {str(e)}"})


if __name__ == "__main__":
    speech_to_text()
